const _ = require('lodash');

module.exports = function(db) {
  const collection = db.collection('statistics-actions');

  const indexes = [
    { key: { date: 1 }, name: 'date_1' },
    { key: { timestamp: 1 }, name: 'timestamp_1' },
    { key: { action: 1 }, name: 'action_1' },
  ];
  collection.createIndexes(indexes);

  return {
    name: 'statisticsAction',
    distinctUsers: function(timestamp, action) {
      const query = { action };
      if (timestamp) query.timestamp = { $gt: timestamp.min, $lt: timestamp.max };
      return collection.distinct('userId', query);
    },

    insertStatisticsAction: function(action) {
      return collection.insertOne(action);
    },

    updateOne: function(selector, update, options) {
      return collection.updateOne(selector, update, {
        upsert: true,
        ...options,
      });
    },

    findStatisticsAction: function(selector, options) {
      const projection = {
        projection: {
          date: 1,
          action: 1,
          activeTime: 1,
          userId: 1,
          cost_cards: 1,
          userCreatedAt: 1,
          online_users: 1,
          server: 1,
          timestamp: 1,
          total_round: 1,
          room_type_name: 1,
          uids: 1,
        },
      };
      return collection.find(selector, { ...projection, ...options }).toArray();
    },
  };
};
